package de.viadee.tools.filefinder;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

public class FileFinder {
	
	public List<File> allFiles = new ArrayList<File>(1024);
	public Set<String> allFilesPathAsString = new HashSet<String>();
	private String startDir = "";

	public static void main(String args[]) {
		FileFinder ff = new FileFinder(System.getProperty("user.dir")
				+ "\\conf\\", "", new String[] { ".props" });

		Iterator<File> iter = ff.getAllFiles().iterator();
		while (iter.hasNext()) {
			String configFilePath = iter.next().getPath();
			doIgnoreCvsFilesFromProject(configFilePath);
		}
	}

	public static void doIgnoreCvsFilesFromEclipseProject(String folderPath,
			String pattern) {
		System.out.println("Looking in path: " + folderPath);

		FileFinder ignoreFiles = new FileFinder(folderPath, pattern,
				new String[] { ".java" });
//		ignoreFiles.writeCvsIgnoreFiles();
		ignoreFiles.writeCvsIgnoreFileToRoot();
		System.out.println(ignoreFiles.getFilesAsString());
	}

	/**
	 * @param configFilePath
	 */
	public static void doIgnoreCvsFilesFromProject(String configFilePath) {
		String pattern = "";
		String path = "";

		Properties properties = new Properties();
		try {
			properties.load(new FileInputStream(new File(configFilePath)));
			pattern = properties.getProperty("pattern");
			path = properties.getProperty("rootDir");
		} catch (Exception e) {

		}

		System.out.println("Looking in path: " + path);

		FileFinder ignoreFiles = new FileFinder(path, pattern,
				new String[] { ".java" });
		ignoreFiles.writeCvsIgnoreFiles();
		System.out.println(ignoreFiles.getFilesAsString());
		System.out.println("Ready!!!");
	}

	public FileFinder(String startDir, String pattern, String extensions[]) {
		Stack<File> dirs = new Stack<File>();
		this.startDir = startDir;
		File startdir = new File(startDir);

		if (startdir.isDirectory())
			dirs.push(startdir);

		while (dirs.size() > 0) {
			for (File file : dirs.pop().listFiles()) {
				if (file.isDirectory()) {
					dirs.push(file);
					continue;
				}
				if ("".equals(pattern)) {
					allFiles.add(file);
					allFilesPathAsString.add(file.getParent());
					continue;
				}
				if (match(file, pattern, extensions)) {
					allFiles.add(file);
					allFilesPathAsString.add(file.getParent());
				}
			}
		}

	}

	public Collection<File> getAllFiles() {
		return allFiles;
	}

	public Set<String> getAllPathAsString() {
		return allFilesPathAsString;
	}

	public String getFilesAsString() {
		String result = "";
		System.out.println("Found " + allFiles.size() + " file"
				+ (allFiles.size() == 1 ? "." : "s."));

		for (File f : allFiles)
			result += f.getAbsolutePath() + "\n";

		return result;
	}

	private static boolean match(File file, String pattern, String suffixes[]) {
		String s = file.getName();
		for (String suffix : suffixes) {
			boolean isRightSuffix = s.length() >= suffix.length()
					&& s.substring(s.length() - suffix.length(), s.length())
							.equalsIgnoreCase(suffix);
			if (isRightSuffix) {
				String path = file.getPath();
				try {
					FileReader reader = new FileReader(path);
					BufferedReader readeBuf = new BufferedReader(reader);
					String ersteZeile = readeBuf.readLine();
					readeBuf.close();
					if (ersteZeile.matches(pattern)) {
						return true;
					}
				} catch (Exception ex) {

				}
			}
		}
		return false;
	}

	/**
	 * @param dateFormat
	 * @param ff
	 */
	private void writeCvsIgnoreFiles() {

		Calendar.getInstance().getTime();
		SimpleDateFormat formater = new SimpleDateFormat("dd.MM.yyyy");
		String dateFormat = formater.format(Calendar.getInstance().getTime());

		int pathNumber = getAllPathAsString().toArray().length;
		for (int i = 0; i < pathNumber; i++) {
			String fileNames = "";
			String pathName = (String) getAllPathAsString().toArray()[i];

			int filesNumber = getAllFiles().toArray().length;
			for (int j = 0; j < filesNumber; j++) {
				File file = (File) getAllFiles().toArray()[j];
				if (file.getParent().equals(pathName)) {
					fileNames += file.getName() + "\n";
				}
			}

			try {
				FileWriter writer = new FileWriter(pathName + "\\.cvsignore");
				writer.write("# " + "THIS FILE WAS GENERATED ON: " + dateFormat
						+ "\n");
				writer.write(fileNames);
				writer.close();
			} catch (Exception e) {
			}
		}
		
		
	}

	private void writeCvsIgnoreFileToRoot() {

		Calendar.getInstance().getTime();
		SimpleDateFormat formater = new SimpleDateFormat("dd.MM.yyyy");
		String dateFormat = formater.format(Calendar.getInstance().getTime());

		String fileNames = "";
		String pathName = startDir;
		String cvsIgnoreRootPath = "";
		int filesNumber = getAllFiles().toArray().length;
		for (int j = 0; j < filesNumber; j++) {
			File file = (File) getAllFiles().toArray()[j];
			cvsIgnoreRootPath = file.getPath();
			cvsIgnoreRootPath = cvsIgnoreRootPath.substring(startDir.length(),cvsIgnoreRootPath.length() );
			cvsIgnoreRootPath = cvsIgnoreRootPath.replaceAll("\\\\", "/");
			if(cvsIgnoreRootPath.startsWith("/")){
				cvsIgnoreRootPath = cvsIgnoreRootPath.substring(1,cvsIgnoreRootPath.length());
			}
			fileNames += cvsIgnoreRootPath + "\n";
		}

		try {
			FileWriter writer = new FileWriter(pathName + "\\.cvsignore");
			writer.write("# " + "THIS FILE WAS GENERATED ON: " + dateFormat
					+ "\n");
			writer.write(fileNames);
			writer.close();
		} catch (Exception e) {
		}
	}
}